package com.ecsolutions.shiro;

import com.ecsolutions.dao.User_DAO;
import com.ecsolutions.entity.TblRole_Entity;
import com.ecsolutions.entity.User_Entity;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * EmployeeShiroRealm
 */
public class EmployeeShiroRealm extends AuthorizingRealm {

    private static final Logger logger = LoggerFactory.getLogger(EmployeeShiroRealm.class);

    @Autowired
    private User_DAO user_dao;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        logger.info("##################执行Shiro权限认证##################");
        String loginName = (String) super.getAvailablePrincipal(principalCollection);
        User_Entity employee = user_dao.getByUserName(loginName);
        if (employee != null) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            return info;
        }
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        logger.info("验证当前Subject时获取到token为：" + ReflectionToStringBuilder.toString(token, ToStringStyle.MULTI_LINE_STYLE));
        User_Entity employee = user_dao.getByUserName(token.getUsername());
        if (employee != null) {
            return new SimpleAuthenticationInfo(employee.getUsername(), employee.getPasswrd(), getName());
        }
        return null;
    }
}